﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Excell_On_Services.Models;
using System.ComponentModel;
using Excell_On_Services.ViewModels;
using System.Web.Security;

namespace Excell_On_Services.Controllers
{
    public class EmployeeController : Controller
    {
        public IEOSRepository Repository { get; set; }
        public IMembershipService MembershipService { get; set; }
        public IFormsAuthenticationService FormsService { get; set; }

        public EmployeeController() :this (new EFEOSRepository())
        {

        }

        public EmployeeController(IEOSRepository repository)
        {
            Repository = repository;
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
        }
        //
        // GET: /Employee/
        [Authorize(Roles = "Administrators")]
        public ActionResult Index([DefaultValue(0)] int pageIndex)
        {
            //int departmentsPerPage = Configuration.Instance.PostPerPage;
            int employeesPerPage = 10;
            return ShowEmployee(
                () => Repository.FindEmployeesInPage(pageIndex, employeesPerPage),
                () => Repository.GetEmployeesCount(),
                pageIndex, "Index", employeesPerPage
                );
        }

        private ActionResult ShowEmployee(Func<IEnumerable<Employee>> filterFunc, Func<int> countFunc, int pageIndex, string actionName, int employeePerPage)
        {
            var employees = filterFunc();
            var employeeCount = countFunc();
            var model = new EmployeesDisplayModel
            {
                Employees = employees,
                PagerModel = new PagerModel
                {
                    CurrentPageIndex = pageIndex,
                    ItemsPerPage = employeePerPage,
                    TotalItems = employeeCount,
                    PageUrlTemplate = Url.Action(actionName, new { pageIndex = PagerModel.PageSymbol })

                }
            };
            return View("Index", model);

        }


        //
        // GET: /Employee/Details/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Details(Guid id)
        {
            var employee = Repository.FindEmployeesById(id);
            MembershipUser currentUser = Membership.Provider.GetUser(employee.aspnet_Users.UserName, true);
            var model = new EmployeeModel
            {
                EmployeeID = employee.EmployeeID,
                username = employee.aspnet_Users.UserName,
                FullName = employee.FullName,
                Email = currentUser.Email,
                Address = employee.Address,
                BirthDate = employee.BirthDate,
                Sex = employee.Sex,
                IsLock = employee.isLock,
                Phone = employee.Phone,
                Notes = employee.Notes,
                DepartmentID = employee.DepartmentID
            };
            return View(model);
        }

        //
        // GET: /Employee/Create
        [Authorize(Roles = "Administrators")]
        public ActionResult Create()
        {
            var item = Roles.GetAllRoles();
            var departments = Repository.FindAllDepartments();
            ViewData["DepartmentItem"] = new SelectList(departments, "DepartmentID", "DepartmentName");
            return View();
        }

        //
        // POST: /Employee/Create

        [HttpPost]
        [Authorize(Roles = "Administrators")]
        public ActionResult Create(EmployeeModel model,FormCollection collecttion)
        {
            try
            {
                // TODO: Add insert logic here
                if (!ModelState.IsValid)
                {
                    var departments = Repository.FindAllDepartments();
                    ViewData["DepartmentItem"] = new SelectList(departments, "DepartmentID", "DepartmentName");
                    return View(model);
                }
                else
                {
                    // Attempt to register the user
                    MembershipCreateStatus createStatus = MembershipService.CreateUser(model.username, model.Password, model.Email);
                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        FormsService.SignIn(model.username, false /* createPersistentCookie */);
                        var employee = new Employee
                        {
                            //aspnet_Users.Createaspnet_Users( = model.username,
                            FullName = model.FullName,
                            Address = model.Address,
                            BirthDate = model.BirthDate,
                            Sex = model.Sex,
                            isLock = model.IsLock,
                            Phone = model.Phone,
                            Notes = model.Notes,
                            DepartmentID = model.DepartmentID
                        };

                        Repository.AddEmployee(employee);
                        Repository.CommitChanges();
                        foreach (string role in Roles.GetAllRoles())
                        {
                            var r = Convert.ToBoolean(collecttion.Get(role));
                            if (r)
                                Roles.AddUserToRole(model.username, role);
                        }
                        return RedirectToAction("Details", new { id = employee.EmployeeID });
                    }
                    else
                    {
                        ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                        return View(model);
                    }
                }
            }
            catch (Exception ex)
            {
                return View(model);
            }
        }
        
        //
        // GET: /Employee/Edit/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Edit(Guid id)
        {
            var departments = Repository.FindAllDepartments();
            ViewData["DepartmentItem"] = new SelectList(departments, "DepartmentID", "DepartmentName");
            var employee = Repository.FindEmployeesById(id);
            MembershipUser currentUser = Membership.Provider.GetUser(employee.aspnet_Users.UserName, true);
            var model = new EmployeeModel
            {
                EmployeeID = employee.EmployeeID,
                username = employee.aspnet_Users.UserName,
                FullName = employee.FullName,
                Email = currentUser.Email,
                Address = employee.Address,
                BirthDate = employee.BirthDate,
                Sex = employee.Sex,
                IsLock = employee.isLock,
                Phone = employee.Phone,
                Notes = employee.Notes,
                DepartmentID = employee.DepartmentID
            };
            return View(model);
        }

        //
        // POST: /Employee/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, EmployeeModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var departments = Repository.FindAllDepartments();
                    ViewData["DepartmentItem"] = new SelectList(departments, "DepartmentID", "DepartmentName");
                    return View(model);
                }
                    
                var item = Repository.FindEmployeesById(model.EmployeeID);
                MembershipUser currentUser = Membership.Provider.GetUser(item.aspnet_Users.UserName, true);
                item.FullName = model.FullName;
                currentUser.Email = model.Email;
                item.Address = model.Address;
                item.BirthDate = model.BirthDate;
                item.Sex = model.Sex;
                item.Phone = model.Phone;
                item.Notes = model.Notes;
                item.isLock = model.IsLock;
                item.DepartmentID = model.DepartmentID;
                Repository.CommitChanges();
                return RedirectToAction("Details", new {id = item.EmployeeID });
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Employee/Delete/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Employee/Delete/5
        [Authorize(Roles = "Administrators")]
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // **************************************
        // URL: /Employee/Update Employee
        // **************************************
        [Authorize(Roles = "Manager,Employee,Administrators")]
        public ActionResult UpdateAccount()
        {

            string username = User.Identity.Name;
            MembershipUser currentUser = Membership.Provider.GetUser(username, true /* userIsOnline 
*/);
            Guid employeeID = Repository.GetIdByUsername(username);
            var model = new EmployeeModel
            {
                username = username,
                Email = currentUser.Email,
            };

            var employee = Repository.FindEmployeesById(employeeID);
            if (employee != null)
            {
                model.Address = employee.Address;
                model.BirthDate = employee.BirthDate;
                model.DepartmentID = employee.DepartmentID;
                model.FullName = employee.FullName;
                model.Email = Membership.GetUser(employee.aspnet_Users.UserName).Email;
                model.Phone = employee.Phone;
                model.Sex = employee.Sex;
                model.username = employee.aspnet_Users.UserName;
                model.Notes = employee.Notes;
            }
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager,Employee,Administrators")]
        public ActionResult UpdateAccount(EmployeeModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                    return View(model);
                string username = User.Identity.Name;
                MembershipUser currentUser = Membership.Provider.GetUser(username, true /* userIsOnline 
*/);
                Guid employeeID = Repository.GetIdByUsername(username);
                currentUser.Email = model.Email;
                var employee = Repository.FindEmployeesById(employeeID);
                if (employee != null)
                {
                    employee.Address = model.Address;
                    employee.BirthDate = model.BirthDate;
                    employee.DepartmentID = model.DepartmentID;
                    employee.FullName = model.FullName;
                    employee.Notes = model.Notes;
                    employee.Phone = model.Phone;
                    employee.Sex = model.Sex;
                }
                else
                {
                    employee = new Employee();
                    employee.EmployeeID = employeeID;
                    employee.Address = model.Address;
                    employee.BirthDate = model.BirthDate;
                    employee.DepartmentID = model.DepartmentID;
                    employee.FullName = model.FullName;
                    employee.Notes = model.Notes;
                    employee.Phone = model.Phone;
                    employee.Sex = model.Sex;
                    Repository.AddEmployee(employee);
                }
                Membership.UpdateUser(currentUser);
                Repository.CommitChanges();
                return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                return View();
            }

        }
    }
}
